package com.ruoyi.web.controller.net;

import com.ruoyi.net.domain.*;
import com.ruoyi.net.netconf.util.DeviceManager;
import com.ruoyi.net.service.INetElementService;
import com.ruoyi.system.service.ISysConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.net.service.IElementQosFlowService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 网元-QOS配置-流分类Controller
 * 
 * @author net
 * @date 2024-11-17
 */
@Api(tags = "网元-QOS配置-流分类")
@RestController
@RequestMapping("/element/qos/flow")
public class ElementQosFlowController extends BaseController {
    @Autowired
    private IElementQosFlowService elementQosFlowService;

    @Autowired
    private INetElementService netElementService;

    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private DeviceManager deviceManager;

    /**
     * 查询网元-QOS配置-流分类列表
     */
    @ApiOperation(value = "查询网元-QOS配置-流分类列表", httpMethod = "GET")
    //    @PreAuthorize("@ss.hasPermi('system:flow:list')")
    @GetMapping("/list")
    public TableDataInfo list(ElementQosFlow elementQosFlow) {
        startPage();
        List<ElementQosFlow> list = elementQosFlowService.selectElementQosFlowList(elementQosFlow);
        return getDataTable(list);
    }

    /**
     * 导出网元-QOS配置-流分类列表
     */
    @ApiOperation(value = "导出网元-QOS配置-流分类列表", httpMethod = "POST")
    //    @PreAuthorize("@ss.hasPermi('system:flow:export')")
    @Log(title = "网元-QOS配置-流分类", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ElementQosFlow elementQosFlow) {
        List<ElementQosFlow> list = elementQosFlowService.selectElementQosFlowList(elementQosFlow);
        ExcelUtil<ElementQosFlow> util = new ExcelUtil<ElementQosFlow>(ElementQosFlow.class);
        util.exportExcel(response, list, "网元-QOS配置-流分类数据");
    }

    /**
     * 获取网元-QOS配置-流分类详细信息
     */
    @ApiOperation(value = "获取网元-QOS配置-流分类详细信息", httpMethod = "GET")
    //    @PreAuthorize("@ss.hasPermi('system:flow:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return success(elementQosFlowService.selectElementQosFlowById(id));
    }

    /**
     * 新增网元-QOS配置-流分类
     */
    @ApiOperation(value = "新增网元-QOS配置-流分类", httpMethod = "POST")
    //    @PreAuthorize("@ss.hasPermi('system:flow:add')")
    @Log(title = "网元-QOS配置-流分类", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ElementQosFlow elementQosFlow) {
        ElementQosFlowMatch qosFlowMatch = elementQosFlow.getQosFlowMatch();
        if (qosFlowMatch != null) {
            elementQosFlow.setMatchRule(qosFlowMatch.getMatchType() + "|" + qosFlowMatch.getMatchRange());
        }

        return toAjax(elementQosFlowService.insertElementQosFlow(elementQosFlow));
    }

    /**
     * 修改网元-QOS配置-流分类
     */
    @ApiOperation(value = "修改网元-QOS配置-流分类", httpMethod = "PUT")
    //    @PreAuthorize("@ss.hasPermi('system:flow:edit')")
    @Log(title = "网元-QOS配置-流分类", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ElementQosFlow elementQosFlow) {
        ElementQosFlowMatch qosFlowMatch = elementQosFlow.getQosFlowMatch();
        if (qosFlowMatch != null) {
            elementQosFlow.setMatchRule(qosFlowMatch.getMatchType() + "|" + qosFlowMatch.getMatchRange());
        }
        return toAjax(elementQosFlowService.updateElementQosFlow(elementQosFlow));
    }

    /**
     * 删除网元-QOS配置-流分类
     */
    @ApiOperation(value = "删除网元-QOS配置-流分类", httpMethod = "DELETE")
    //    @PreAuthorize("@ss.hasPermi('system:flow:remove')")
    @Log(title = "网元-QOS配置-流分类", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(elementQosFlowService.deleteElementQosFlowByIds(ids));
    }

    /**
     * 激活设备
     *
     * @param id
     */
    @ApiOperation(value = "激活设备", httpMethod = "GET")
    @Log(title = "激活设备", businessType = BusinessType.UPDATE)
    @GetMapping(value = "/activate/{id}")
    public AjaxResult activateDevice(@PathVariable("id") String id) {
        ElementQosFlow entity = elementQosFlowService.selectElementQosFlowById(id);
        entity.setStatus("1");
        if (sendXml(entity)) {
            return toAjax(elementQosFlowService.updateElementQosFlow(entity));
        } else {
            return AjaxResult.error("激活设备失败");
        }
    }

    /**
     * 去激活设备
     *
     * @param id
     */
    @ApiOperation(value = "去激活设备", httpMethod = "GET")
    @Log(title = "去激活设备", businessType = BusinessType.UPDATE)
    @GetMapping(value = "/unactivate/{id}")
    public AjaxResult unactivateDevice(@PathVariable("id") String id) {
        ElementQosFlow entity = elementQosFlowService.selectElementQosFlowById(id);
        entity.setStatus("0");
        if (sendXml(entity)) {
            return toAjax(elementQosFlowService.updateElementQosFlow(entity));
        } else {
            return AjaxResult.error("去激活设备失败");
        }
    }
    /*<qos-cfgs xmlns="http://fiberhome.com/fhnw/yang/qos/fos-qos">
    <qos-tpl>
      <traffic-class-cfgs>
        <traffic-class-cfg>
          <class-name>gr4</class-name>
          <operator>all</operator>
          <match-ipv4-precedence-cfg>
            <ipv4-precedence>0</ipv4-precedence>
          </match-ipv4-precedence-cfg>
        </traffic-class-cfg>
      </traffic-class-cfgs>
    </qos-tpl>
  </qos-cfgs>*/

    private boolean sendXml(ElementQosFlow entity) {
        boolean isSend = true;
        // TODO: 2024/11/28  设备联调，添加并激活
        if (sysConfigService.selectDebugEnabled()) {
            NetElement netElement = netElementService.getCacheObject(entity.getElementId());
            deviceManager.getDevice(netElement.getIp());
            String operation = "create";
            if ("0".equals(entity.getStatus())) {
                operation = "remove";
            }

            ElementQosFlowMatch qosFlowMatch = entity.getQosFlowMatch();

            StringBuilder xml = new StringBuilder();
            // TODO: 2025/02/05 测验对比，调整
            xml.append("<qos-cfgs xmlns=\"http://fiberhome.com/fhnw/yang/qos/fos-qos\">" +
                    "    <qos-tpl>" +
                    "      <traffic-class-cfgs>" +
                    "        <traffic-class-cfg>" +
                    "          <class-name>" + entity.getClassifyName() + "</class-name>" +
//                    "          <operator>" + entity.getLogicRelation() + "</operator>");
                    "          <operator>" + "all" + "</operator>");
            // 匹配IP优先级 match-ipv4-precedence-cfg
//            if (qosFlowMatch != null && "qos:match-ipv4-precedence".equalsIgnoreCase(qosFlowMatch.getMatchType())) {
            xml.append("          <match-ipv4-precedence-cfg>" +
                    "            <ipv4-precedence>" + qosFlowMatch.getMatchRange() + "</ipv4-precedence>" +
                    "          </match-ipv4-precedence-cfg>");
//            }
            xml.append("        </traffic-class-cfg>" +
                    "      </traffic-class-cfgs>" +
                    "    </qos-tpl>" +
                    "  </qos-cfgs>");
            System.out.println(xml.toString());
            isSend = deviceManager.editConfig(xml.toString(), "merge");
        }
        return isSend;
    }
}